<template>
  <el-dialog
    title="机构选择"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="clearDataList()"
    width="85vw"
    top="5vh"
    append-to-body
  >
    <el-container>
      <el-main style="height: 70vh; overflow-x: hidden">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="5">
            <div class="boxsty">
              <el-tree
                ref="treeSelect"
                :data="treeData"
                @check="handleCheckChange"
                show-checkbox
                check-strictly
                :props="defaultProps"
                :filter-node-method="filterNode"
                class="filter-tree"
                node-key="id"
                highlight-current
                :default-expanded-keys="[1]"
                accordion
                @node-click="getNodeData"
              >
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="无数据权限"
                    placement="right-start"
                    v-if="data.isLock"
                  >
                    <span>{{ node.label }} <i class="el-icon-lock"></i></span>
                  </el-tooltip>
                  <span v-if="!data.isLock">{{ node.label }}</span>
                </span>
              </el-tree>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8">
            <div class="boxsty" v-if="showPrise">
              <div class="flex titbottom">
                <el-input
                  v-model="listQuery.name"
                  placeholder="请输入搜索用户"
                  style="margin-right: 10px"
                ></el-input>

                <el-button
                  @click="btnSearch"
                  type="primary"
                  icon="el-icon-search"
                  plain
                >搜索</el-button
                >
              </div>
              <div class="avue-crud">
                <el-table
                  @row-click="handleClick"
                  :data="tableDataDept"
                  v-loading="tableloading"
                  style="width: 100%"
                >
                  <el-table-column
                    prop="lly"
                    label="联络员"
                    width="80"
                  ></el-table-column>
                  <el-table-column
                    prop="username"
                    label="用户"
                    width="100"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                  <el-table-column
                    prop="ryName"
                    label="姓名"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                </el-table>
              </div>
              <div style="margin-top: 20px">
                <el-pagination
                  @size-change="sizeChangeHandle"
                  @current-change="currentChangeHandle"
                  :current-page="page.currentPage"
                  :page-sizes="[10, 20, 50, 100]"
                  :page-size="page.pageSize"
                  :total="page.total"
                  background
                  layout="total, sizes, prev, pager, next"
                >
                </el-pagination>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="11">
            <div class="boxsty">
              <div class="tabletext titbottom">已选择机构</div>
              <div class="avue-crud">
                <el-table
                  :data="lastPage == 'ndts' ? tableDataOrgSingle : tableDataOrg"
                  ref="jg-table"
                  stripe
                >
                  <el-table-column
                    prop="deptName"
                    label="部门"
                    min-width="220"
                  ></el-table-column>
                  <el-table-column
                    v-if="lastPage == 'ndcj'"
                    prop="ryName"
                    label="联络员"
                    width="100"
                  ></el-table-column>
                  <el-table-column fixed="right" label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button
                        plain
                        @click="delOrgList(scope.$index, scope.row.deptId)"
                        type="danger"
                        plain
                      >删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="tabletext titbottom" style="margin-top: 20px">
                已选择人员
              </div>
              <div class="avue-crud">
                <el-table :data="tableDataUser" ref="ry-table" stripe>
                  <el-table-column
                    prop="deptName"
                    label="部门"
                    width="120"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                  <el-table-column
                    prop="lly"
                    label="联络员"
                    width="80"
                  ></el-table-column>
                  <el-table-column
                    prop="username"
                    label="用户"
                    width="100"
                  ></el-table-column>
                  <el-table-column
                    prop="ryName"
                    label="姓名"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                  <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button
                        plain
                        @click="delUserList(scope.$index)"
                        type="danger"
                        plain
                      >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <!-- <div v-if="lastPage == 'ndts'" style="margin-top: 20px">
                 <div>
                   <el-checkbox v-model="checked1" label="发约人"></el-checkbox>
                   <el-checkbox v-model="checked2" label="受约人"></el-checkbox>
                 </div>
               </div>
               <div v-if="lastPage == 'rwsndts'" style="margin-top: 20px">
                 <el-checkbox v-model="bkhr" label="被考核人"></el-checkbox>
               </div>-->
            </div>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <span slot="footer" class="dialog-footer">
      <el-button plain type="primary" v-if="canSubmit" @click="btnSave"
      >确定</el-button
      >
      <el-button type="primary" plain @click="btnCancel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
    import store from "@/store";
    import { fetchTree } from "@/api/admin/dept";

    import { showJgTree,fetchUserList } from "@/api/dailyExamine/targetExamine/createAssessment";
    import { validatenull } from "@/util/validate";

    export default {
        data() {
            return {
                token: "",
                type: "",
                qjDeptId: "", //全局部门id
                qjGzId: "", //全局规则id
                tableloading: false, //table遮挡
                showPrise: true,
                showRentPrise: true,
                visible: false,
                canSubmit: false,
                tableDataDept: [],
                tableDataUser: [],
                tableDataOrg: [],
                tableDataOrgSingle: [],
                ids: [],
                dataForm: {},
                listQuery: {
                    name: "",
                },
                treeData: [],
                jgtreeData: [],
                defaultProps: {
                    children: "children",
                    label: "name",
                },
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20, // 每页显示多少条,
                    isAsc: false, // 是否倒序
                },
                searchForm: {},
                zdySearchForm: {},
                nodeKey: [],
                lastPage: "",
                selectOrgId: [],
                checked1: false,
                checked2: false,
                bkhr: false,
            };
        },
        watch: {
            tableDataOrg: {
                handler(newVal) {
                    if (newVal.length > 0) {
                        this.selectOrgId = newVal.map((item) => item.deptId);
                        //this.$refs.treeSelect.setCheckedKeys(this.selectOrgId);
                    } else {
                        this.selectOrgId = [];
                    }
                    this.$nextTick(() => {
                        this.$refs.treeSelect.setCheckedKeys(this.selectOrgId);
                    });
                },
                deep: true,
                immediate: true,
            },

        },
        created() {},
        methods: {
            init(id, type, jsonData, lastPage) {
                this.token = store.getters.access_token;
                this.type = type;
                this.qjGzId = id;
                this.ids = jsonData;
                this.visible = true;
                this.canSubmit = true;
                this.lastPage = lastPage;
                //this.loadTableDataUser(id);
                this.getList();
                this.clearDataList();
                this.checked1 = false;
                this.checked2 = false;
                this.bkhr = false;
            },
            getList() {
                showJgTree().then((response) => {
                    this.treeData = response.data.data;
                    this.showPrise = true; // 机构人员显示
                    this.showRentPrise = false; // 机构隐藏
                });
            },
            jiequ(data) {
                const result = data.map((item) => {
                    const children = item.children.map((every) => {
                        return {
                            id: every.id,
                            parentId: every.parentId,
                            name: every.name,
                            deptName: every.deptName,
                            deptCode: every.deptCode,
                            isLock: every.isLock,
                        };
                    });
                    return {
                        ...item,
                        children: children,
                    };
                });
                return result;
            },
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            getPersons(page, params, selectOrg) {
                this.tableloading = true;
                fetchUserList(
                    Object.assign(
                        {
                            current: page.currentPage,
                            size: page.pageSize,
                        },
                        params,
                        this.searchForm,
                        this.zdySearchForm
                    )
                )
                    .then((response) => {
                        this.tableDataDept = response.data.data.records;
                        this.page.total = response.data.data.total;
                        this.tableloading = false;
                        if (selectOrg) {
                            //选择机构
                            const obj = this.tableDataDept.find((item) => item.lly == "是");
                            const arr = this.tableDataDept.filter((item) => item.lly == "是");
                            if (obj && arr.length > 0) {
                                this.$message.closeAll();
                                if (this.lastPage == "ndcj") {
                                    this.tableDataUser = [];
                                    this.tableDataOrg = [];
                                    this.tableDataOrgSingle = [];
                                    this.selectOrgId = [];
                                }
                                this.$refs.treeSelect.setCheckedKeys([]);
                                //tableDataOrgSingle用于在指标拟定的时候显示在页面（同一个机构有多个联络员只显示一个联络员的数据）；tableDataOrg是真正用于传值的数据
                                const index = this.tableDataOrgSingle.findIndex(
                                    (item) => item.userId == obj.userId
                                );
                                if (index == -1) {
                                    this.tableDataOrgSingle.push(obj);
                                }
                                arr.forEach((arrObj) => {
                                    const index = this.tableDataOrg.findIndex(
                                        (item) => item.userId == arrObj.userId
                                    );
                                    if (index == -1) {
                                        this.selectOrgId.push(this.qjDeptId);
                                    }
                                });
                                this.tableDataOrg.push(arr[0]);
                            } else {
                                this.$message.closeAll();
                                this.$message.warning("公司领导日常考核管理员未设置！");
                            }
                            this.$refs.treeSelect.setCheckedKeys(this.selectOrgId);
                        }
                    })
                    .catch((err) => {
                        this.tableloading = false;
                    });
            },
            getNodeData(data) {
                if (this.type != "jg") {
                    this.page.currentPage = 1;
                    this.qjDeptId = data.id;
                    this.getPersons(this.page, {
                        deptId: data.id,
                    });
                } else {
                    this.handleClick(data);
                }
            },
            handleCheckChange(data, checked, indeterminate) {
                if (this.type != "jg") {
                    this.page.currentPage = 1;
                    this.qjDeptId = data.id;
                    this.getPersons(
                        this.page,
                        {
                            deptId: data.id,
                        },
                        true
                    );
                } else {
                    this.handleClick(data);
                }
            },
            //选人添加到右边的框
            handleClick(vm) {
                for (var i = 0; i < this.tableDataUser.length; i++) {
                    if (this.tableDataUser[i].username == vm.username) {
                        return;
                    }
                }
                if (this.lastPage == "ndcj") {
                    this.tableDataUser = [];
                    this.tableDataOrg = [];
                    this.tableDataOrgSingle = [];
                    this.$refs.treeSelect.setCheckedKeys([]);
                }
                let objUser = {
                    hzId: this.qjGzId,
                    deptName: vm.deptName,
                    deptId: vm.deptId,
                    userId: vm.userId,
                    lly: vm.lly,
                    username: vm.username,
                    ryName: vm.ryName,
                    type: vm.type,
                };
                this.tableDataUser.push(objUser);
            },
            //删除人员list
            delUserList(index) {
                this.tableDataUser.splice(index, 1);
            },
            delOrgList(index, deptId) {
                if (this.lastPage == "ndts") {
                    this.tableDataOrgSingle.splice(index, 1);
                    this.tableDataOrg = this.tableDataOrg.filter(
                        (item) => item.deptId != deptId
                    );
                } else {
                    this.tableDataOrg.splice(index, 1);
                }
            },
            //清空记录
            clearDataList() {
                this.qjDeptId = "";
                this.tableDataDept = [];
                this.tableDataUser = [];
                this.tableDataOrg = [];
                this.tableDataOrgSingle = [];

            },
            //保存拟定推送
            btnSave() {
                this.$message.closeAll();
                console.log(this.checked1,this.checked2)
                if (
                    this.tableDataOrg.length == 0 &&
                    this.tableDataUser.length == 0 &&
                    !this.checked1 &&
                    !this.checked2 && this.lastPage != "rwsndts"
                ) {
                    this.$message.warning("请至少选择一条数据！");
                    return false;
                } else if (this.lastPage == "ndcj" && this.tableDataOrg.length > 1) {
                    this.$message.warning("只能选择一条数据！");
                    return false;
                }  else if( this.tableDataOrg.length == 0 && this.tableDataUser.length == 0 && this.lastPage == "rwsndts" && !this.bkhr){
                    this.$message.warning("请至少选择一条数据！");
                    return false;
                }
                this.canSubmit = false;
                this.visible = false;
                var paramUser = [];
                for (var i = 0; i < this.tableDataUser.length; i++) {
                    paramUser[i] = {
                        userId: this.tableDataUser[i].userId,
                        deptId: this.tableDataUser[i].deptId,
                        deptName: this.tableDataUser[i].deptName,
                        ryName: this.tableDataUser[i].ryName,
                        userCode: this.tableDataUser[i].username
                    };
                }
                const paramOrg = this.tableDataOrg.map((item) => {
                    const temp = {};
                    if (item) {
                        temp.userId = item.userId;
                        temp.deptId = item.deptId;
                        temp.deptName = item.deptName;
                        temp.ryName = item.ryName;
                        temp.userCode = item.username;
                    }
                    return temp;
                });
                const tgLx = paramOrg.length > 0 ? "1" : "2";
                var fayue = 0;
                var shouyue = 0;
                var bkhr = 0;
                if (this.bkhr) {
                    bkhr = 1;
                }
                if (this.checked1) {
                    fayue = 1;
                }else{
                    fayue = 0;
                }
                if (this.checked2) {
                    shouyue = 1;
                }else{
                    shouyue = 0;
                }
                console.log(shouyue,fayue)
                var params = {
                    ids: this.ids,
                    tableDataUser: paramUser,
                    selectorgdata: paramOrg,
                    tgLx: tgLx,
                    type: this.type,
                    fayue,
                    shouyue,
                    bkhr,
                };
                this.$nextTick(()=>{
                    this.$emit("submitfy", params);
                })
            },
            // tree搜索事件,搜索人
            btnSearch() {
                let param = {
                    deptId: this.qjDeptId,
                };

                if (this.listQuery.name.trim() !== "") {
                    param["username"] = this.listQuery.name.trim();
                    param["ryName"] = this.listQuery.name.trim();
                }
                this.getPageUsers(param);
            },
            // 分页
            // 每页数
            sizeChangeHandle(val) {
                this.page.pageSize = val;
                this.page.currentPage = 1;
                this.getPageUsers();
            },
            // 当前页
            currentChangeHandle(val) {
                this.page.currentPage = val;
                this.getPageUsers();
            },
            //分页刷新
            getPageUsers(vm) {
                if (vm) {
                    this.getPersons(this.page, vm);
                } else {
                    this.getPersons(this.page, {
                        deptId: this.qjDeptId,
                    });
                }
            },
            //取消按钮
            btnCancel() {
                this.visible = false;
                this.clearDataList();
            },
            //判空
            validatenull(val) {
                return validatenull(val);
            },
        },
    };
</script>

<style scoped>
</style>
